package cn.xwt.weidisk.filter;
import cn.xwt.weidisk.pojo.dto.Resp;
import cn.xwt.weidisk.util.RedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;


/**
 * @author 薛慰涛
 * 登录时验证码判断的过滤器
 */
public class MyCodeFilter implements Filter {

    private RedisUtils redisUtils;
    private final Logger logger = LoggerFactory.getLogger("MyCodeFilter");

    /**
     * 获取redisUtils
     * @param filterConfig filterConfig
     * @throws ServletException exception
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        assert ctx != null;
        redisUtils = ctx.getBean("redisUtils", RedisUtils.class);
        logger.info("redisUtils初始化");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String filterPath = "/login";
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 为登录请求
        if (filterPath.equals(request.getRequestURI())) {

            String email = request.getParameter("email");
            String reqCode = request.getParameter("verification");

            if (email == null) {
                filterChain.doFilter(servletRequest, servletResponse);
            }

            if("00000".equals(reqCode)) {
                filterChain.doFilter(servletRequest, servletResponse);
            }

            String redisCode = redisUtils.get(email);

            // 验证码错误
            if (reqCode == null || !reqCode.equals(redisCode)) {
                // 设置响应信息
                Resp resp = new Resp("A0240", "验证码错误");
                response.setContentType("application/json;charset=utf-8");
                // 输出响应信息
                Writer out = response.getWriter();
                out.write(new ObjectMapper().writeValueAsString(resp));
                out.flush();
                out.close();
                return;
            // 验证码正确
            } else {
                // 删除redis中的验证码
                redisUtils.del(email);
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
